    //
//  GameMainView.m
//  linkingGame
//
//  Created by 李佳 on 15/4/5.
//  Copyright (c) 2015年 com.jinWu. All rights reserved.
//

#import "GameMainView.h"
#import "ChallengeLevelData.h"
#import "MapMaker.h"
#import <objc/runtime.h>

@interface GameMainView ()

@property(nonatomic, assign)NSUInteger totalTime; //总的时间进度
@property(nonatomic, assign)NSUInteger timesTime; //单次的时间进度


@property(nonatomic, assign)NSUInteger resetTime;
@property(nonatomic, assign)NSUInteger addTime;

@property(nonatomic, assign)BOOL isStartGame;
@property(nonatomic, assign)BOOL isPauseState;

@property(nonatomic, strong)UIView* pauseView;
@property(nonatomic, strong)UIView* gamePassView;
@property(nonatomic, strong)UIView* gameFailView;

@property(nonatomic, assign)NSUInteger removePairCount;
@property(nonatomic, assign)NSUInteger pairTotalCount;

@property(nonatomic, strong)NSDate* gameBeginDate;

@property(nonatomic, strong)UIButton* gameResetBtn;
@property(nonatomic, strong)UIButton* gameRemoveBtn;
@end

@implementation GameMainView

- (instancetype)initWithLevelData:(id<LevelData>)levelData andFrame: (CGRect)rect
{
    if (self = [super initWithFrame:rect])
    {
        self.isStartGame = NO;
        [self initLLKBtnWithLevelData:levelData];
        if (levelData.gameMode == KChallengeMode)
            [self initRandomTimerForChallenge:levelData];
        
        
        self.gameBeginDate = [NSDate date];
        [self initProgressViewForClassic:levelData];
        self.pairTotalCount = levelData.curRowNum * levelData.curCloNum / 2;
        [self initPauseButton];
        [self initGameResetButton];
        [self initGameRemoveButton];
        self.removePairCount = 0;
    }
    return self;
}

- (void)initPauseButton
{
    UIButton* pauseBtn = [[UIButton alloc] init];
    pauseBtn.backgroundColor = [UIColor blueColor];
    pauseBtn.frame = CGRectMake(rightLeftEmptySpace, self.frame.size.height - GetbtmLeftEmptySpace() - 40, 40, 40);
    [pauseBtn addTarget:self action:@selector(pauseButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [pauseBtn setTitle:@"P" forState:UIControlStateNormal];
    [self addSubview:pauseBtn];
}

- (void)initGameResetButton
{
    UIButton* resetBtn = [[UIButton alloc] init];
    resetBtn.backgroundColor = [UIColor blueColor];
    resetBtn.frame = CGRectMake(self.frame.size.width - rightLeftEmptySpace - 40, self.frame.size.height - GetbtmLeftEmptySpace() - 40, 40, 40);
    [resetBtn addTarget:self action:@selector(resetButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [resetBtn setTitle:@"1" forState:UIControlStateNormal];
    self.gameResetBtn = resetBtn;
    [self addSubview:resetBtn];
}

- (void)initGameRemoveButton
{
    UIButton* removeBtn = [[UIButton alloc] init];
    removeBtn.backgroundColor = [UIColor blueColor];
    removeBtn.frame = CGRectMake(self.frame.size.width - rightLeftEmptySpace - (2 * 40 + 2), self.frame.size.height - GetbtmLeftEmptySpace() - 40, 40, 40 );
    [removeBtn addTarget:self action:@selector(removeButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [removeBtn setTitle:@"3" forState:UIControlStateNormal];
    self.gameRemoveBtn = removeBtn;
    [self addSubview:removeBtn];
}


- (void)initProgressViewForClassic:(ClassLevelData*)levelData
{
    self.totalProgressView = [[ProgressView alloc] init];
    CGPoint centerPoint = self.center;
    CGRect rect = CGRectMake(centerPoint.x - (self.frame.size.width - 60) / 2, 40, self.frame.size.width - 60, 15);
    self.totalProgressView.frame =  rect;
    [self addSubview:self.totalProgressView];
    
    self.totalTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(setTotleProgress) userInfo:nil repeats:YES];
    self.totalTime = levelData.totalTime;
    
    if (levelData.gameMode == KClassicMode)
    {
        self.timesProgressView = [[ProgressView alloc] init];
        rect = CGRectMake(centerPoint.x - (self.frame.size.width - 200) / 2, 60  , self.frame.size.width - 200, 15);
        self.timesProgressView.frame = rect;
        [self addSubview:self.timesProgressView];
        
        self.timerTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(setTimesProgress) userInfo:nil repeats:YES];
        self.timesTime = levelData.intervalTime;
    }
}

-(void)initRandomTimerForChallenge: (ChallengeLevelData*)levelData
{
    self.resetTime = levelData.mapResetTime;
    self.addTime = levelData.addRandPairTime;
}


- (void)initLLKBtnWithLevelData: (id<LevelData>)levelData //利用图片资源直接加载 不需要从本地区取了
{
    NSUInteger btnWidth = GetBtnSizeByDevice();
    
    CGRect mainRect = [UIScreen mainScreen].bounds;
    
    //获取开始位置
    CGFloat beginX = (mainRect.size.width - (btnWidth * levelData.curCloNum + levelData.curCloNum - 1)) / 2;
    CGFloat beginY = topLeftEmptySpace + (((mainRect.size.height - topLeftEmptySpace - GetbtmLeftEmptySpace()) - (btnWidth * levelData.curRowNum + levelData.curRowNum - 1)) / 2);
    
    for (NSUInteger i = 1; i <= levelData.curRowNum; ++i)
    {
        NSArray* rowDatas = levelData.gameMapArray[i];
        for (NSUInteger j = 1; j <= levelData.curCloNum; j++)
        {
            CGRect btnRect = CGRectMake(beginX + (btnWidth + 1) * (j - 1),  beginY + (btnWidth + 1) * (i - 1), btnWidth, btnWidth);
            
            ClickButton* tmpBtn = [[ClickButton alloc] init];
            tmpBtn.frame = btnRect;
            
            tmpBtn.layer.cornerRadius = 5;
            tmpBtn.layer.masksToBounds = YES;
            tmpBtn.index = [rowDatas[j] intValue];
            tmpBtn.position = CGPointMake(j, i);
            NSString* pathName = [[NSUserDefaults standardUserDefaults] valueForKey:@"linkingGameSelectedExpression"];
            NSString* fileName = [NSString stringWithFormat:@"%@_%ld", pathName, (unsigned long)tmpBtn.index];
            [tmpBtn setImage:[UIImage imageNamed:fileName] forState:UIControlStateNormal];
            [tmpBtn addTarget:self action:@selector(LLKBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            tmpBtn.backgroundColor = [UIColor redColor];
            [self addSubview:tmpBtn];
        }
    }
}

- (void)addPauseViewToGame
{
    UIAlertAction *nextPassAction = [UIAlertAction actionWithTitle:@"继续"  style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self continueButtonClicked:nil];
    }];
    
    UIAlertAction *reStartAction = [UIAlertAction actionWithTitle:@"重置游戏" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self reStartGameBtnClicked:nil];
    }];
    
    UIAlertAction *goBackAction = [UIAlertAction actionWithTitle:@"回到主菜单" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self goBackBtnClicked:nil];
    }];
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"暂停游戏"
                                                                             message:[NSString stringWithFormat:@"换成图%@",@""]
                                                                      preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:nextPassAction];
    [alertController addAction:reStartAction];
    [alertController addAction:goBackAction];
    [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
    
    
}

- (void)continueButtonClicked: (id)sender
{
    [self.pauseView removeFromSuperview];
    [self pauseButtonClicked:nil];
}

- (void)nextGamePassBtnClicked: (id)sender
{
    [self.gamePassView removeFromSuperview];
    [self.delegate nextGamePassBtnClicked];
}

- (void)reStartGameBtnClicked: (id)sender
{
    [self.gamePassView removeFromSuperview];
    [self.gameFailView removeFromSuperview];
    
    [self.delegate reStartGameBtnClicked];
}

- (void)goBackBtnClicked: (id)sender
{
    [self.pauseView removeFromSuperview];
    [self.gamePassView removeFromSuperview];
    [self.delegate goToBack];
}

- (void)pauseButtonClicked: (id)sender
{
    if (!self.isPauseState)
    {
        //停止定时器
        [self.totalTimer setFireDate:[NSDate distantFuture]];
        [self.timerTimer setFireDate:[NSDate distantFuture]];
        [self.resetMapTimer setFireDate:[NSDate distantFuture]];
        [self.addRandomPairTimer setFireDate:[NSDate distantFuture]];
        
        [self addPauseViewToGame];
    }
    else
    {
        //重新开始定时器
        [self.totalTimer setFireDate:[NSDate date]];
        [self.timerTimer setFireDate:[NSDate date]];
        [self.resetMapTimer setFireDate:[NSDate date]];
        [self.addRandomPairTimer setFireDate:[NSDate date]];
    }
    self.isPauseState = !self.isPauseState;
}

- (void)resetButtonClicked: (id)sender
{
    [self.pauseView removeFromSuperview];
    [self.delegate resetLLKMap];
    self.timesProgressView.progress = 1;
    
    NSString* title = self.gameResetBtn.titleLabel.text;
    int value = [title intValue];
    value--;
    [self.gameResetBtn setTitle:[NSString stringWithFormat:@"%d", value] forState:UIControlStateNormal];
    if (value == 0)
    {
        [self.gameResetBtn setUserInteractionEnabled: NO];
    }
}

- (void)removeButtonClicked: (id)sender
{
    if([self.delegate removeOnePairOfMap])
    {
        self.removePairCount++;
        NSString* title = self.gameRemoveBtn.titleLabel.text;
        int value = [title intValue];
        value--;
        [self.gameRemoveBtn setTitle:[NSString stringWithFormat:@"%d", value] forState:UIControlStateNormal];
        if (value == 0)
        {
            [self.gameRemoveBtn setUserInteractionEnabled: NO];
        }
        self.timesProgressView.progress = 1;
    }
}

- (void)resetLLKMapWithLevelData: (id<LevelData>)levelData
{
    NSUInteger btnWidth = GetBtnSizeByDevice();
    
    CGRect mainRect = [UIScreen mainScreen].bounds;
    
    //获取开始位置
    CGFloat beginX = (mainRect.size.width - (btnWidth * levelData.curCloNum + levelData.curCloNum - 1)) / 2;
    CGFloat beginY = topLeftEmptySpace + (((mainRect.size.height - topLeftEmptySpace - GetbtmLeftEmptySpace()) - (btnWidth * levelData.curRowNum + levelData.curRowNum - 1)) / 2);
    
    for (UIView* tmpView in [self subviews])
    {
        if ([tmpView isKindOfClass: [ClickButton class]])
        {
            [tmpView removeFromSuperview];
        }
    }
    
    
    for (NSUInteger i = 1; i <= levelData.curRowNum; ++i)
    {
        NSArray* rowDatas = levelData.gameMapArray[i];
        for (NSUInteger j = 1; j <= levelData.curCloNum; j++)
        {
            if ([rowDatas[j] intValue] == 0)
                continue;
            CGRect btnRect = CGRectMake(beginX + (btnWidth + 1) * (j - 1),  beginY + (btnWidth + 1) * (i - 1), btnWidth, btnWidth);
            
            ClickButton* tmpBtn = [[ClickButton alloc] init];
            tmpBtn.frame = btnRect;
            
            tmpBtn.layer.cornerRadius = 5;
            tmpBtn.layer.masksToBounds = YES;
            tmpBtn.index = [rowDatas[j] intValue];
            tmpBtn.position = CGPointMake(j, i);
       
            NSString* pathName = [[NSUserDefaults standardUserDefaults] valueForKey:@"linkingGameSelectedExpression"];
            NSString* fileName = [NSString stringWithFormat:@"%@_%ld", pathName, (unsigned long)tmpBtn.index];
            [tmpBtn setImage:[UIImage imageNamed:fileName] forState:UIControlStateNormal];
            [tmpBtn addTarget:self action:@selector(LLKBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            tmpBtn.backgroundColor = [UIColor redColor];
            [self addSubview:tmpBtn];
        }
    }    
}

- (void)addGamePassView
{
    UIAlertAction *nextPassAction = [UIAlertAction actionWithTitle:@"下一关" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self nextGamePassBtnClicked:nil];
    }];
    
    UIAlertAction *reStartAction = [UIAlertAction actionWithTitle:@"再来一次" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self reStartGameBtnClicked:nil];
    }];
    
    UIAlertAction *goBackAction = [UIAlertAction actionWithTitle:@"回到主菜单" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self goBackBtnClicked:nil];
    }];
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"恭喜过关！"
                                                                             message:[NSString stringWithFormat:@"换成图%@",@""]
                                                                      preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:nextPassAction];
    [alertController addAction:reStartAction];
    [alertController addAction:goBackAction];
    [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
    
    
    [self.addRandomPairTimer invalidate];
    self.addRandomPairTimer = nil;
    [self.resetMapTimer invalidate];
    self.resetMapTimer = nil;
    self.isStartGame = NO;
    self.pairTotalCount = 0;
}

- (void)addGameFailView
{
    //1.回到主菜单。再次挑战。
    UIAlertAction *reStartAction = [UIAlertAction actionWithTitle:@"再来一次" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self reStartGameBtnClicked:nil];
    }];
    
    UIAlertAction *goBackAction = [UIAlertAction actionWithTitle:@"回到主菜单" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self goBackBtnClicked:nil];
    }];
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"挑战失败！"
                                                                             message:[NSString stringWithFormat:@"换成图%@",@""]
                                                                      preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:reStartAction];
    [alertController addAction:goBackAction];
    [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
    
    
    [self.addRandomPairTimer invalidate];
    self.addRandomPairTimer = nil;
    [self.resetMapTimer invalidate];
    self.resetMapTimer = nil;
    self.isStartGame = NO;
    self.pairTotalCount = 0;
}


- (void)LLKBtnClick: (ClickButton*)clickBtn
{
    //发生消除了  而且需要进行增加格子或者随机打乱。
    if([self.delegate LLKBtnClick:clickBtn])
    {
        if (!self.isStartGame && ([self.delegate getGameMode] == KChallengeMode))
        {
            self.isStartGame = YES;
            self.addRandomPairTimer = [NSTimer scheduledTimerWithTimeInterval:self.addTime target:self selector:@selector(addRandomPairWithTimer) userInfo:nil repeats:YES];
            self.resetMapTimer = [NSTimer scheduledTimerWithTimeInterval:self.resetTime target:self selector:@selector(resetLLKmapWithTimer) userInfo:nil repeats:YES];
        }
        
        //游戏结束 过关了
        
        if (++self.removePairCount == self.pairTotalCount)
        {
            [self addGamePassView];
            self.totalProgressView.progress = 0.0;
            [self saveGamePassStars];
            [self.totalTimer setFireDate:[NSDate distantFuture]];
            [self.timerTimer setFireDate:[NSDate distantFuture]];
        }
        //NSLog(@"self.removePairCount = %lu", (unsigned long)self.removePairCount);
    }
}

- (void)resetLLKmapWithTimer
{
    [self.delegate resetLLKMap];
}

- (void)addRandomPairWithTimer
{
    if([self.delegate addRandomPairToMap])
    {
        self.pairTotalCount++;
        //NSLog(@"self.pairTotalCount = %lu", (unsigned long)self.pairTotalCount);
    }
}

- (void)setTotleProgress
{
    self.totalProgressView.progress = self.totalProgressView.progress - (1.0f / self.totalTime);
    if (self.totalProgressView.progress - 0 < 0.0001)
    {
        [self.totalTimer setFireDate:[NSDate distantFuture]];
        [self.timerTimer setFireDate:[NSDate distantFuture]];
        [self addGameFailView];
    }
}
- (void)setTimesProgress
{
    self.timesProgressView.progress = self.timesProgressView.progress - (1.0f / self.timesTime);
    if (self.timesProgressView.progress - 0 < 0.0001)
    {
        self.totalProgressView.progress = 0.0;
        [self.totalTimer setFireDate:[NSDate distantFuture]];
        [self.timerTimer setFireDate:[NSDate distantFuture]];
        [self addGameFailView];
    }
}
//保存玩家过关之后的星级
- (void)saveGamePassStars
{
    //判断依据是总时间和所花时间
    NSString* gameModeKey = nil;
    if ([self.delegate getGameMode] == KClassicMode)
        gameModeKey = classicModeStars;
    else
        gameModeKey = challengeModeStars;
    
    NSUserDefaults *gameDefaults = [NSUserDefaults standardUserDefaults];
    NSMutableArray* defaultsArr = [gameDefaults objectForKey:gameModeKey];
    
    if (defaultsArr == nil) //之前没有
    {
        defaultsArr = [[NSMutableArray alloc] init];
        for (int i = 0; i < gamePassCount; ++i)
        {
            [defaultsArr addObject:[NSNumber numberWithInt:0]];
        }
    }
    
    NSMutableArray* gameModeStars = [NSMutableArray arrayWithArray:defaultsArr];
    //获取当前关卡的stars
    int  curPassStar = [self getGamePassStar];
    int lastPlayPassStar = [gameModeStars[[self.delegate getGameLevel] - 1] intValue];
    if (curPassStar > lastPlayPassStar)
    {
        [gameModeStars replaceObjectAtIndex:[self.delegate getGameLevel] - 1 withObject:[NSNumber numberWithInt:curPassStar]];
    }
    
    [gameDefaults setObject:gameModeStars forKey:gameModeKey];
}

- (int)getGamePassStar
{
    int gamePassStart = 0;

    NSDate* curDate = [NSDate date];
    NSCalendar *cal = [NSCalendar currentCalendar];
    
    unsigned int unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSDateComponents *d = [cal components:unitFlags fromDate:self.gameBeginDate toDate:curDate options:0];
    
    int sec = (int)([d hour] * 3600 + [d minute] * 60 + [d second]);
    
    float percentage = (float)sec / self.totalTime;
    if (percentage > 0.0 && percentage < 0.20)
        gamePassStart = 6;
    else if (percentage > 0.20 && percentage < 0.25)
        gamePassStart = 5;
    else if (percentage > 0.25 && percentage < 0.35)
        gamePassStart = 4;
    else if (percentage > 0.35 && percentage < 0.45)
        gamePassStart = 3;
    else if (percentage > 0.45 && percentage < 0.55)
        gamePassStart = 2;
    else
        gamePassStart = 1;
 
    return gamePassStart;
}


- (void)dealloc
{
    [self.addRandomPairTimer invalidate];
    self.addRandomPairTimer = nil;
    [self.resetMapTimer invalidate];
    self.resetMapTimer = nil;
    
}

@end
